package com.quan.weixin.rpc.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.quan.base.common.base.service.support.BaseService;
import com.quan.base.common.exception.BizException;
import com.quan.weixin.rpc.api.WeixinArticleGroupArticleService;
import com.quan.weixin.rpc.api.WeixinArticleGroupService;
import com.quan.weixin.rpc.dao.mapper.WeixinArticleGroupMapper;
import com.quan.weixin.rpc.model.WeixinArticle;
import com.quan.weixin.rpc.model.WeixinArticleGroup;
import com.quan.weixin.rpc.model.WeixinArticleGroupArticle;

@Service
public class WeixinArticleGroupServiceImpl extends BaseService<WeixinArticleGroup, Integer> implements WeixinArticleGroupService {

	@Autowired
	private WeixinArticleGroupMapper mapper;
	
	@Autowired
	private WeixinArticleGroupArticleService articleGroupArticleService ;
	
	@Override
	public int delete(Integer id) throws BizException {
		this.articleGroupArticleService.deleteByGroupId(id);
		return super.delete(id);
	}
	
	@Transactional
	@Override
	public void insertArticleGroupArticle(Integer id, List<Integer> articleIds) {
		
		if(null != articleIds && !articleIds.isEmpty()) {
			for (Integer articleId : articleIds) {
				Integer selectCountArticleIdByGroupId = this.articleGroupArticleService.selectCountArticleIdByGroupId(id, articleId) ;
				
				//判断该组是否已存在该图文，如果存在则不再添加进该组
				if(null == selectCountArticleIdByGroupId || selectCountArticleIdByGroupId == 0) {
					WeixinArticleGroupArticle articleGroupArticle = new WeixinArticleGroupArticle() ;
					articleGroupArticle.setArticleGroupId(id);
					articleGroupArticle.setArticleId(articleId);
					
					this.articleGroupArticleService.insertSelective(articleGroupArticle) ;
				}
				
			}
		}
	}

	@Override
	public int getArticleCount(Integer groupId) {
		return this.articleGroupArticleService.getArticleCount(groupId);
	}

	@Override
	public List<WeixinArticle> getArticles(Integer groupId) {
		return this.mapper.getArticles(groupId);
	}

}
